/*
* INSANE - Interactive Structural Analysis Environment
*
* Copyright (C) 2003-2005
* Universidade Federal de Minas Gerais
* Escola de Engenharia
* Departamento de Engenharia de Estruturas
* 
* Author's email :    insane@dees.ufmg.br
* Author's website :  http://www.dees.ufmg.br/insane
* 
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/
package br.ufmg.dees.insane.ui.rich.prep.view.command;

import java.awt.Toolkit;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;

import br.ufmg.dees.insane.commons.command.Command;
import br.ufmg.dees.insane.commons.view.ExtensionFileFilter;
import br.ufmg.dees.insane.model.prep.GeoPrepModel;
import br.ufmg.dees.insane.ui.rich.prep.view.DesktopPrep;
import br.ufmg.dees.insane.ui.rich.prep.view.InterfacePrep;

/**
 * This class is a implementation of the interface Command.
 * its unabled to undo or redo.
 * its "execute" method verify the existence of a model, and
 * if that is one, it calls a file chooser to set the models name and
 * the save routine is called.
 *
 * @author Ferreira, Reginaldo & Pitangueira, Roque
 * @since 05/07/2006
 * @see prep_view.command.AAAcommand
 */
public class SaveFileAsCommand implements Command {
    
    private DesktopPrep parent;
	private JFileChooser fileChooser = new JFileChooser();
    private ExtensionFileFilter filter = new ExtensionFileFilter("isn", "INSANE-PREP Files");
	private boolean validFile;
	private GeoPrepModel model;
    
//*****************************************************************************
	
    /**
     * Creates new SaveAsFileCommand
     * and sets the FileFilter to FileChooser.
     *
     * @param parent The JFrame parent.
     */
    public SaveFileAsCommand(JFrame parent) {
        this.parent = (DesktopPrep)parent;
        fileChooser.setFileFilter(filter);
    }
    
//*****************************************************************************
	
    /**
     * Saves the current model accordding to ModelState name.
     * Prompts a dialog to choose another model name.
     *
     * @see gui.command.AAAcommand#execute()
     */
    public void execute()
    {
    	InterfacePrep intFrame = (InterfacePrep)parent.getDesktop().getSelectedFrame();
    	
    	if(intFrame instanceof InterfacePrep)
    	{
    		model = (GeoPrepModel)intFrame.getModel();
    			
    		validFile = false;
    		while (!validFile)
    		{
    			fileChooser.setCurrentDirectory(new File(model.getPath()));
    			fileChooser.setDialogTitle("Save as");
    			
    			int retVal = fileChooser.showSaveDialog(parent);
    			
    			if (retVal == JFileChooser.APPROVE_OPTION)
    			{
    					
    				//Getting the file name
    				String s = fileChooser.getSelectedFile().getName();
    				
    				// Sets the model's name
    				//model.setName(s);
    					
    				//Getting the file extension
    				String ext = new String();
    				int i = s.lastIndexOf('.');
    				if (i > 0 &&  i < s.length() - 1) {
    					ext = s.substring(i+1).toLowerCase();
    				}
    					
    				//Comparing the extension
    				if (!ext.equals("isn"))
    				{
    					s = s + ".isn";
    					File file = fileChooser.getSelectedFile();
    						
    					//Changing the file in case of no good extensions
    					fileChooser.setSelectedFile(new File(file.getParent() + File.separator + s));
    				}
    					
    				//Checks if the file exists
    				if (fileChooser.getSelectedFile().exists())
    				{
    					int value = 10;
    					value = JOptionPane.showConfirmDialog(parent, 
    							"File \"" + fileChooser.getSelectedFile().getPath() + "\" exists.\nDo you want to replace it?",
    							"Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    					if (value == JOptionPane.YES_OPTION)
    					{
    						validFile = true;
    					}
    				}
    				else
    				{
    					validFile = true;
    				}
    			}
    			else return;
    		}// while
    		
    		model.setName(fileChooser.getSelectedFile().getName().replaceAll(".isn",""));
    		
			// Informs the model that its file exists
			model.setHasFile(true);
			
			// Informs the model that its file exists
			model.setIsModified(false);
			
			// Sets the model's path
			model.setPath(fileChooser.getSelectedFile().getPath());
			
    		save();	
    	}
    }
    
//*****************************************************************************
	
    /**
     * Writes model on disc using a FileOutputStream and
     * an ObjectOutputStream.
     */
    private void save() {
    	if(parent.getDesktop().getSelectedFrame() instanceof InterfacePrep)
    	{
    		try
    		{
                FileOutputStream serialStream = new FileOutputStream(fileChooser.getSelectedFile());
                ObjectOutputStream stream = new ObjectOutputStream(serialStream);
                stream.writeObject((GeoPrepModel)((InterfacePrep)parent.getDesktop().getSelectedFrame()).getModel());
                serialStream.flush();
                
                // Rename the title of the views
                this.updateIntFrameTitle();
                
                parent.getDesktopTextArea().addText("The model was saved as:  " + model.getPath());
            }
    		catch (Exception exc)
    		{
                Toolkit.getDefaultToolkit().beep();
                JOptionPane.showMessageDialog(parent, "Couldn't save file!", "ERROR Message", JOptionPane.ERROR_MESSAGE);
            }
    	}	
    }
    
//  ****************************************************************************
    
    /** Updates the title off all views from the current model. */
    private void updateIntFrameTitle()
    {
    	JInternalFrame desktopViews[] = parent.getDesktop().getAllFrames();
        InterfacePrep view;
        
        for (int i=0; i<desktopViews.length; i++)
        {
        	view = ((InterfacePrep)desktopViews[i]);
        	if (view.getModel().equals(model) == true)
        	{
        		view.setTitle(model.getName() + " - " + view.getName());
        	}
        }      	
    }    
    
//  ****************************************************************************
	
    /**
     * Impossible to undo - not implemented.
     */
    public void undo() {}
    
//  ****************************************************************************
	
    /**
     * Impossible to redo - not implemented.
     */
    public void redo() {}
    
//  ****************************************************************************
}

